<template>
  <div class="dialog-wrapper">
    <Modal
      title="生成收款二维码"
      footer-hide
      :value="value"
      :mask-closable="false"
      @on-cancel="handleCancel">
      <Form
        ref="qrForm"
        :label-width="80"
        :model="qrForm"
        :rules="qrRules">
        <FormItem label="收款金额" prop="money">
          <Input type="text" v-model="qrForm.money" placeholder="请输入收款金额" number />
        </FormItem>
        <FormItem label="收款方式" prop="repayWay">
          <Select v-model="qrForm.repayWay" placeholder="请选择收款方式">
            <Option :value="1">支付宝</Option>
            <Option :value="2">微信</Option>
          </Select>
        </FormItem>
        <FormItem style="margin-bottom: 5px;">
          <Button type="primary" @click="handleCreate" :loading="createSpin">生成收款二维码</Button>
          <p>注意：修改金额/收款方式后，请重新生成二维码</p>
        </FormItem>
      </Form>
      <div class="create-code">
        <!-- <h3 class="create-code-tip">此处生成二维码</h3> -->
        <p class="create-code-info">
          {{ qrObject.name | nameFormat }}_{{ qrObject.cellphone | phoneFormat }}_{{ qrForm.money }}
        </p>
        <div class="qrcode" ref="qrcode" id="qrcode">
          <Spin fix v-show="createSpin"></Spin>
        </div>
        <Button type="success" class="download" @click="handleDownload" v-if="process">下载</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import QRCode from 'qrcodejs2';
  import { deepCopy, drawFormat } from '@/libs/util';
import { type } from 'os';

  export default {
    name: 'createQrcode',
    props: {
      value: {
        type: Boolean,
        default: false
      },
      qrData: {
        type: Object,
        default: function() {
          return {}
        }
      }
    },
    data () {
      const validateMoney = (rule, value, callback) => {
				const { shouldRepayMoney } = this.qrObject;
        if (value <= 0) {
          callback(new Error('收款金额不能为0'));
        } else if (value > shouldRepayMoney) {
          callback(new Error('收款金额不能大于应还金额'));
        } {
          callback();
        }
			};
      return {
        createSpin: false,
        process: false,
        codeEle: '',
        qrForm: {
          money: '',
          orderId: '',
          repayChannel: 'joinpay',
          repayWay: ''
        },
        qrRules: {
          money: [
            { required: true, type: 'number', message: '请输入收款金额', trigger: 'blur' },
            { validator: validateMoney, trigger: 'blur' }
          ],
          repayWay: [
            { required: true, type: 'number', message: '请选择收款方式', trigger: 'change' }
          ]
        },
        qrObject: {}
      }
    },
    watch: {
      value (newValue) {
        if (newValue) {
          this.qrObject = deepCopy(this.qrData);
          this.qrForm.orderId = this.qrObject.orderId;
          this.qrForm.money = this.qrObject.money;
        }
      }
    },
    methods: {
      // 取消事件
      handleCancel() {
        this.createSpin = false;
        this.process = false;
        this.$refs.qrForm.resetFields();
        this.removeQRCodeHtml();
        this.codeEle = '';
        this.$emit('input', false);
      },
      // 清空二维码和按钮
      removeQRCodeHtml() {
        if (this.codeEle) {
          let parent = document.getElementById('qrcode');
          let canvas = parent.getElementsByTagName('canvas')[0];
          let image = parent.getElementsByTagName('img')[0];
          parent.removeChild(canvas);
          parent.removeChild(image);
        }
      },
      // 生成收款二维码
      handleCreate() {
        const { qrcode } = this.$refs;
        this.$refs.qrForm.validate(valid => {
          if (valid) {
            this.removeQRCodeHtml();
            this.process = false;
            this.createSpin = true;
            this.$http.post('/helsinki/admin/order/unionpay/payment-link', {
              ...this.qrForm
            }).then(({ data: { data, errcode, info } }) => {
              if (errcode == 0) {
                this.codeEle = new QRCode(qrcode, {
                  text: decodeURI(data),
                  width: 150,
                  height: 150,
                  colorDark: '#000000',
                  colorLight: '#ffffff',
                  correctLevel: QRCode.CorrectLevel.H
                });
                this.$Message.success('生成二维码成功');
                this.process = true;
              }
              this.createSpin = false;
            }).catch(err => {
              this.createSpin = false;
            });
          }
        })
      },
      // base64 convert blob对象
      base64ConvertToBlob(base64) {
        let base64Arr = base64.split(',');
        let imgType = '';
        let base64String = '';
        if(base64Arr.length > 1) {
          //如果是图片base64，去掉头信息
          base64String = base64Arr[1];
          imgType = base64Arr[0].substring(base64Arr[0].indexOf(':') + 1, base64Arr[0].indexOf(';'));
        }
        // 将base64解码
        let bytes = atob(base64String);
        let bytesCode = new ArrayBuffer(bytes.length);
        // 转换为类型化数组
        let byteArray = new Uint8Array(bytesCode);

        // 将base64转换为ascii码
        for (var i = 0; i < bytes.length; i++) {
          byteArray[i] = bytes.charCodeAt(i);
        }

        // 生成Blob对象（文件对象）
        return new Blob( [bytesCode] , {type : imgType});
      },
      // 判断是否为IE，或者IE下的Edge浏览器
      isIE() {
        const useragent = window.navigator.userAgent;
        return !!window.ActiveXObject || "ActiveXObject" in window || useragent.indexOf('Edge') > -1;
      },
      // 下载图片
      handleDownload() {
        const { cellphone } = this.qrObject;
        const { repayWay } = this.qrForm;
        let qrImage = document.getElementById('qrcode').getElementsByTagName('img')[0];
        let imgSrc = qrImage.getAttribute('src');
        let way = repayWay === 1 ? 'alipay' : repayWay == 2 ? 'wechat' : '';
        let fileName = way + '_' + drawFormat(cellphone, 'x', 3, 4);

        if (this.isIE()) {
          let blob = this.base64ConvertToBlob(imgSrc);
          window.navigator.msSaveBlob(blob, `${fileName}.png`);
        } else {
          let link = document.createElement('a');
          link.href = imgSrc;
          link.download = `${fileName}.png`;
          link.click();
        }
      }
    },
    filters: {
      nameFormat(val) {
        if (!val) return;
        let newVal = typeof val !== 'string' ? toString(val) : val;
        return `*${newVal.substr(1)}`
      },
      phoneFormat(val) {
        if (!val) return;
        let newVal = typeof val !== 'string' ? toString(val) : val;
        let startLen = newVal.length - 4;
        return newVal.substr(startLen);
      }
    }
  }
</script>

<style lang="scss" scoped>
  .create-code {
    padding: 20px;
    background: #f0f0f0;
    text-align: center;
    .create-code-tip {
      margin-bottom: 10px;
    }
    .create-code-info {
      margin-bottom: 10px;
    }
    .qrcode {
      position: relative;
      margin: 0 auto;
      padding: 10px;
      width: 170px;
      height: 170px;
      background: #ffffff;
    }
  }

  .download {
    margin-top: 10px;
    width: 170px;
  }
</style>
